using MediatR;
using WeatherMcpServer.Data.Entities;
using WeatherMcpServer.Data.Repositories;

namespace WeatherMcpServer.Application.Alerts.Commands;

/// <summary>
/// 创建预警的命令。
/// </summary>
public record CreateWeatherAlertCommand(
    WeatherType Type,
    AlertSeverity Severity,
    string? RegionCode,
    string? RegionName,
    double? TemperatureMax,
    double? TemperatureMin,
    double? RainMm,
    double? WindLevel,
    string? Message
) : IRequest<long>;

/// <summary>
/// 处理器：写入数据库并返回新预警ID。
/// </summary>
public class CreateWeatherAlertHandler : IRequestHandler<CreateWeatherAlertCommand, long>
{
    private readonly IWeatherAlertRepository _repo;

    public CreateWeatherAlertHandler(IWeatherAlertRepository repo)
    {
        _repo = repo;
    }

    public async Task<long> Handle(CreateWeatherAlertCommand request, CancellationToken cancellationToken)
    {
        var entity = new WeatherAlert
        {
            Type = request.Type,
            Severity = request.Severity,
            RegionCode = request.RegionCode,
            RegionName = request.RegionName,
            TemperatureMax = request.TemperatureMax,
            TemperatureMin = request.TemperatureMin,
            RainMm = request.RainMm,
            WindLevel = request.WindLevel,
            Message = request.Message,
            Status = AlertStatus.New,
            CreatedAt = DateTime.UtcNow
        };
        await _repo.AddAsync(entity, cancellationToken);
        await _repo.SaveChangesAsync(cancellationToken);
        return entity.Id;
    }
}
